package net.borderwars.vm;

import net.borderwars.util.Histagram;

import java.util.Stack;

/**
 * @author Eric
 *         Date: Feb 26, 2005
 *         Time: 1:35:13 PM
 */
public class StackOverflowException extends Error {
    Stack stack = null;
    private boolean debugMode;

    public StackOverflowException(Stack stack, boolean debugMode) {
        this.stack = stack;
        this.debugMode = debugMode;
    }

    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("Stack Overflow\n");

        try {
            if (debugMode) {
                Histagram h = new Histagram();
                for (Object o : stack) {
                    VirtualMachine.DebugStackElement dse = (VirtualMachine.DebugStackElement) o;
                    h.count(dse.getMethod() + "[" + dse.getIdx() + "]");
                }
                sb.append("Elements Allocated at these locations\n");
                sb.append(h.toString());
                sb.append("Stack contains");
                sb.append(stack.toString());
            } else {
                sb.append(stack.toString());
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return (sb.toString());
    }

}
